<template>
    <div class="login">
        <div class="loginFlat">
            <h1>用户登录</h1>
            <el-form>
                <el-form-item label="账号:">
                    <el-input v-model="user.id"></el-input>
                </el-form-item>
                <el-form-item label="密码:">
                    <el-input     type="password" v-model="user.password" show-password></el-input>
                </el-form-item>
            </el-form>
            <el-button @click="gotohome">登录 </el-button>
            <el-button @click="regist">没有账号？</el-button>
            <el-button @click="tview">游客浏览</el-button>
    </div>
  </div>
</template>

<script>
import { ref, reactive, getCurrentInstance } from 'vue';
import { useUserStore } from '../plugins/pinia';  // 使用 Pinia 中定义的 UserStore

export default {
  setup() {
    // 获取组件实例的 proxy，用于访问 $axios 和 $router 等属性
    const { proxy } = getCurrentInstance();

    // 用户信息对象，使用 reactive 使其成为响应式的
    const user = reactive({
      id: '',
      name: '',
      gender: '',
      age: '',
      permission: '',
      password: '',
      email: ''
    });

    // 获取 Pinia 的用户 Store
    const userStore = useUserStore();

    // 登录成功函数
    const success_f = (response) => {
      proxy.$message({
        message: response.data.msg,
        type: 'success'
      });
    };

    // 登录失败函数
    const fail_f = (response) => {
      proxy.$message({
        message: response.data.msg,
        type: 'error'
      });
    };

    // 登录方法
    const gotohome = () => {
      proxy.$axios.post('/login', user).then((response) => {
        if (response.data.code) {
          success_f(response);
          userStore.setUserInfo(response.data.data); // 登录成功后设置用户信息到 Pinia Store
          console.log(userStore)
          proxy.$router.push('/home');
        } else {
          fail_f(response);
        }
      }).catch((error) => {
        console.error("请求失败:", error);
      });
    };

    const tview = () =>{
      const tourist = {
      id: 0,
      name: '',
      gender: '',
      age: '',
      permission: 0,
      password: '',
      email: ''
    };
      userStore.setUserInfo(tourist)
      console.log('a')
      proxy.$router.push('/home')
    };

    // 注册方法
    const regist = () => {
      proxy.$router.push('/register');
    };

    return {
      user,
      gotohome,
      regist,
      success_f,
      fail_f,
      tview
    };
  }
};
</script>


